package com.movie.service.impl;

import com.movie.entity.ESMovie;
import com.movie.entity.ESStar;
import com.movie.entity.Movie;
import com.movie.entity.Star;
import com.movie.mapper.StarMapper;
import com.movie.service.IStarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.movie.vo.PageResultVO;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lxx
 * @since 2021-04-13
 */
@Service
public class StarServiceImpl extends ServiceImpl<StarMapper, Star> implements IStarService {

    @Autowired(required = false)
    private StarMapper mapper;

    @Autowired
    private ElasticsearchRestTemplate template;

    /**
     * 初始化演员信息
     * @throws Exception
     */
    @Override
    public void initStar() throws Exception {
        //1.获取演员信息 存入ES
        List<Star> starList = mapper.initStar();
        List<Movie> movieList = starList.get(0).getMovieList();
        List<String> mainMovieList=new ArrayList<>();//该集合装载演员的主演电影
        movieList.forEach(movie -> {
            mainMovieList.add(movie.getMovieName());
        });
        template.deleteIndex(ESStar.class);
        template.createIndex(ESStar.class);
        template.putMapping(ESStar.class);
        starList.forEach(star->{
            ESStar esStar=new ESStar();
            esStar.setStarId(star.getStarId());
            esStar.setEnglishName(star.getEnglishName());
            esStar.setFensNum(star.getFensNum());
            esStar.setStarName(star.getStarName());
            esStar.setStarPic(star.getStarPic());
            esStar.setMainMovieList(mainMovieList);
            esStar.setStatus(star.getStatus());
            template.save(esStar);
        });
    }

    /**
     * 根据关键字在影人中进行查找
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public PageResultVO<ESStar> searchStarByKeyWord(Map map) throws Exception {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();//构建查询条件
        Object keyword = map.get("keyword");
        if (!StringUtils.isEmpty(keyword)){
            //如果关键字不为空 添加过滤条件
            MatchQueryBuilder starNameQueryBuilder = QueryBuilders.matchQuery("starName", keyword);
            MatchQueryBuilder movieListQueryBuilder = QueryBuilders.matchQuery("mainMovieList", keyword);
            MatchQueryBuilder starStatusQueryBuilder=QueryBuilders.matchQuery("status",0);
            boolQueryBuilder.should(starNameQueryBuilder);
            boolQueryBuilder.should(movieListQueryBuilder);
            boolQueryBuilder.should(starNameQueryBuilder);//过滤已经上架的

            //分页
            PageRequest page=null;
            if (!StringUtils.isEmpty(map.get("currentPage"))&&!StringUtils.isEmpty(map.get("pageSize"))){
                Integer currentPage = (Integer) map.get("currentPage");
                Integer pageSize = (Integer) map.get("pageSize");
                page=PageRequest.of(currentPage-1,pageSize);
            }else {
                page=PageRequest.of(0,5);
            }

            NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder()
              .withQuery(boolQueryBuilder)
              .withPageable(page);

            NativeSearchQuery nativeSearchQuery = builder.build();
            SearchHits<ESStar> resultHits = template.search(nativeSearchQuery, ESStar.class);
            long totalHits = resultHits.getTotalHits();//总数量
            List<SearchHit<ESStar>> searchHits = resultHits.getSearchHits();
            List<ESStar> esStarList=new ArrayList<>();
            System.out.println(esStarList);
            searchHits.forEach(hit->{
                ESStar content = hit.getContent();
                esStarList.add(content);
            });
            return new PageResultVO<ESStar>(true,totalHits,"查询成功",esStarList);
        }else {
            return new PageResultVO<>(false,"参数不正确");
        }
    }

    @Override
    public PageResultVO getAllStar() throws Exception {
        NativeSearchQueryBuilder builder=new NativeSearchQueryBuilder();

        //根据粉丝数进行排序
        SortBuilder sortBuilder=null;
        sortBuilder=SortBuilders.fieldSort("fensNum").order(SortOrder.DESC);
        builder.withSort(sortBuilder);

        NativeSearchQuery nativeSearchQuery = builder.build();
        SearchHits<ESStar> resultHits = template.search(nativeSearchQuery, ESStar.class);
        if (resultHits==null){
            return new PageResultVO(false,"无数据");
        }
        long totalHits = resultHits.getTotalHits();
        List<SearchHit<ESStar>> searchHits = resultHits.getSearchHits();
        List<ESStar> esStarsList=new ArrayList<>();//设置一个集合装载数据
        searchHits.forEach(hit->{
            ESStar content = hit.getContent();
            esStarsList.add(content);
        });
        return new PageResultVO(true,totalHits,"查询成功",esStarsList);
    }


    @Autowired
    private FreeMarkerConfig freeMarkerConfig;

    /**
     * 生成明星的静态化页面
     * @param starId
     * @throws Exception
     */
    @Override
    public void getStarHtml(String starId) throws Exception {
        Configuration configuration = freeMarkerConfig.getConfiguration();
        Template template = configuration.getTemplate("starIntroduce.ftl");
        Map starMap=new HashMap();
        Writer out=new FileWriter("D:\\Nginx\\nginx-1.18.0\\starPages"+"/"+starId+".html");
        template.process(starMap,out);
        out.close();
    }
}
